import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:poet/pages/share_page/compoents/bkg_img_group.dart';
import 'package:poet/pages/theme_config.dart';
import 'package:uuid/uuid.dart';
import 'package:share/share.dart';

class SelectBkgPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SelectBkgPage();
  }
}

class _SelectBkgPage extends State<SelectBkgPage> {
  var uuid = new Uuid();

  GlobalKey _globalKey = new GlobalKey();

  final String _content = '''白日放歌须纵酒，青春作伴好还乡。
即从巴峡穿巫峡，便下襄阳向洛阳。
''';

  BkgItemModel _item = null;

  Future<Uint8List> _capturePng() async {
    try {
      print('inside');
      RenderRepaintBoundary boundary =
          _globalKey.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      var pngBytes = byteData.buffer.asUint8List();
      setState(() {});
      return pngBytes;
    } catch (e) {
      print(e);
      rethrow;
    }
  }

  Future<String> _savePng({bool showToast: true}) async {
    Uint8List bytes = await _capturePng();
    final directory = await getApplicationDocumentsDirectory();
    final newUuid = uuid.v1();

    final file = File('${directory.path}/$newUuid.png');
    file.writeAsBytes(bytes);
    if (showToast) {
      Fluttertoast.showToast(
        msg: "已保存到图片到目录：${directory.path}",
        gravity: ToastGravity.BOTTOM,
        textColor: Colors.white,
      );
    }
    return file.path;
  }

  void _sharePng() async {
    String filePath = await _savePng(showToast: false);

    Share.image(
        path: filePath,
        mimeType: ShareType.TYPE_IMAGE,
        title: "分析",
        text: "测试");

    Fluttertoast.showToast(
      msg: "分享:$filePath",
      gravity: ToastGravity.BOTTOM,
      textColor: Colors.white,
    );
  }

  DecorationImage _buildImageDecoration() {
    bool showImage = _item != null && _item.url != null;
    if (!showImage) {
      return null;
    }
    return DecorationImage(
      image: AssetImage(
        _item.url,
      ),
      fit: BoxFit.fitWidth,
      alignment: Alignment.bottomCenter,
    );
  }

  Widget _buildPoetContent() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        RepaintBoundary(
          key: _globalKey,
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minWidth: double.infinity,
              minHeight: 120,
            ),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                image: _buildImageDecoration(),
              ),
              child: Padding(
                padding: EdgeInsets.all(12),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(
                      width: 1.3,
                      style: BorderStyle.solid,
                      color: Color(ThemeConfig.weakColor),
                    ),
                  ),
                  child: Padding(
                    padding: EdgeInsets.symmetric(vertical: 12, horizontal: 20),
                    child: DefaultTextStyle(
                      style: Theme.of(context).textTheme.body1.copyWith(
                            fontFamily: 'hyqts',
                            fontSize: 20,
                            height: 1.5,
                          ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: <Widget>[
                          Text(
                            _content,
                            textAlign: TextAlign.left,
                          ),
                          SizedBox(
                            height: 24,
                          ),
                          Text(
                            "《无情》李益",
                            textAlign: TextAlign.right,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _onItemChange(BkgItemModel item) {
    setState(() {
      this._item = item;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("选择背景"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.file_download),
            onPressed: _savePng,
          ),
          IconButton(
            icon: Icon(Icons.share),
            onPressed: _sharePng,
          ),
        ],
      ),
      body: Container(
        color: Color(ThemeConfig.mainBackColor),
        child: Column(
          children: <Widget>[
            Expanded(
              child: _buildPoetContent(),
            ),
            BkgItemGroup(
              onItemChange: _onItemChange,
            ),
          ],
        ),
      ),
    );
  }
}
